<template>
  <div class="cabinet-view" :key="props.totalU">
    <!-- 机柜主体 -->
    <div class="cabinet-container">
      <!-- 使用一个容器来包裹可滚动区域 -->
      <div class="scroll-container" ref="scrollContainerRef" @scroll="handleScroll">
        <div class="u-ruler">
          <div v-for="i in props.totalU" :key="i" class="u-number">
            <span>{{ i }}U</span>
          </div>
        </div>
        <div class="slots-container">
          <div
            v-for="i in props.totalU"
            :key="i"
            class="slot"
            :class="{
              occupied: isOccupied(i),
              selected: isSelected(i),
              selectable: isSelectable(i),
              disabled: !isSelectable(i) && !isOccupied(i),
            }"
            @mousedown="isSelectable(i) && handleSlotMouseDown(i)"
            @mousemove="isSelectable(i) && handleSlotMouseMove(i)"
            @mouseup="handleSlotMouseUp"
            @mouseleave="handleSlotMouseUp"
          >
            <div class="slot-content">
              <div class="mount-holes">
                <span class="hole" />
                <span class="hole" />
              </div>
              <span class="device-name">
                {{
                  getDeviceName(i) || (isFirstSelected(i) ? `新设备 (${props.serverSize}U)` : '')
                }}
              </span>
              <div class="mount-holes">
                <span class="hole" />
                <span class="hole" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 图例 -->
    <div class="legend">
      <div class="legend-item">
        <span class="color-block occupied"></span>
        <span>已占用</span>
      </div>
      <div class="legend-item">
        <span class="color-block selected"></span>
        <span>已选择</span>
      </div>
      <div class="legend-item">
        <span class="color-block selectable"></span>
        <span>可选择</span>
      </div>
      <div class="legend-item">
        <span class="color-block disabled"></span>
        <span>尺寸不支持</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, watchEffect } from 'vue'
import { nextTick } from 'vue'

interface OccupiedSlot {
  start: number
  size: number
  deviceName: string
}

interface Props {
  totalU: number
  occupiedSlots: OccupiedSlot[]
  modelValue: number
  serverSize?: number
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: number]
}>()

const isDragging = ref(false)
const startPosition = ref<number | null>(null)
const endPosition = ref<number | null>(null)

const selectedPosition = computed({
  get: () => props.modelValue,
  set: (value) => {
    if (value > 0 && value <= props.totalU) {
      emit('update:modelValue', value)
    }
  },
})

const scrollContainerRef = ref<HTMLElement | null>(null)

// 检查位置是否被占用
const isOccupied = (position: number) => {
  return props.occupiedSlots.some(
    (slot) => position >= slot.start && position < slot.start + slot.size,
  )
}

// 获取设备名称
const getDeviceName = (position: number) => {
  const slot = props.occupiedSlots.find(
    (slot) => position >= slot.start && position < slot.start + slot.size,
  )
  return slot?.deviceName
}

// 检查是否是选中区域的第一个位置
const isFirstSelected = (position: number) => {
  return position === selectedPosition.value
}

// 检查位置是否被选中
const isSelected = (position: number) => {
  if (!props.serverSize) return position === selectedPosition.value
  return position >= selectedPosition.value && position < selectedPosition.value + props.serverSize
}

// 检查位置是否可选
const isSelectable = (position: number) => {
  // 如果当前位置被占用，直接返回 false
  if (isOccupied(position)) return false

  // 如果没有指定服务器大小，只要当前位置未被占用就可选
  if (!props.serverSize) return true

  // 检查是否超出机柜范围
  if (position + props.serverSize - 1 > props.totalU) {
    return false
  }

  // 检查是否有足够的连续空间
  for (let i = 0; i < props.serverSize; i++) {
    if (isOccupied(position + i)) {
      return false
    }
  }
  return true
}

// 处理槽位事件
const handleSlotMouseDown = (position: number) => {
  if (!isSelectable(position)) return
  isDragging.value = true
  startPosition.value = position
  endPosition.value = position
}

const handleSlotMouseMove = (position: number) => {
  if (!isDragging.value) return
  endPosition.value = position
}

const handleSlotMouseUp = () => {
  if (isDragging.value && startPosition.value) {
    selectedPosition.value = startPosition.value
  }
  isDragging.value = false
  startPosition.value = null
  endPosition.value = null
}

// 处理滚动事件
const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement
  // 同步滚动位置
  const rulerEl = target.querySelector('.u-ruler')
  const slotsEl = target.querySelector('.slots-container')
  if (rulerEl && slotsEl) {
    rulerEl.scrollTop = target.scrollTop
    slotsEl.scrollTop = target.scrollTop
  }
}

// 滚动到选中位置
const scrollToSelected = () => {
  if (!scrollContainerRef.value || !props.serverSize) return
  const container = scrollContainerRef.value
  const totalHeight = container.scrollHeight
  const viewHeight = container.clientHeight
  const itemHeight = 32 // 固定每个U的高度为32px
  const selectedPos = props.modelValue

  // 计算滚动位置，使选中项在视图中间
  const scrollTop = Math.max(0, totalHeight - selectedPos * itemHeight - viewHeight / 2)
  container.scrollTo({ top: scrollTop, behavior: 'smooth' })
}

// 计算内容高度
const updateContentHeight = () => {
  if (scrollContainerRef.value) {
    const rulerEl = scrollContainerRef.value.querySelector('.u-ruler')
    const slotsEl = scrollContainerRef.value.querySelector('.slots-container')
    if (rulerEl && slotsEl) {
      // 确保高度计算正确
      const height = `${props.totalU * 32}px` // 32px 是每个 U 的高度
      rulerEl.style.height = height
      slotsEl.style.height = height
      // 强制重新计算滚动位置
      nextTick(() => {
        scrollToSelected()
      })
    }
  }
}

// 监听选中位置变化
watch(
  () => props.modelValue,
  () => {
    scrollToSelected()
  },
)

// 监听 totalU 的变化，更新内容高度
watchEffect(() => {
  //props.totalU // 依赖收集
  nextTick(() => {
    updateContentHeight()
  })
})

// 监听总高度变化，确保位置合法
watch(
  () => props.totalU,
  (newTotal) => {
    // 如果当前选择的位置超出新的总高度，重置为1
    if (props.modelValue > newTotal) {
      emit('update:modelValue', 1)
    }
    // 确保在高度变化时更新内容
    nextTick(() => {
      updateContentHeight()
    })
  },
  { immediate: true },
)

// 组件挂载后滚动到选中位置
onMounted(() => {
  scrollToSelected()
  // 动态设置内容高度
  if (scrollContainerRef.value) {
    const rulerEl = scrollContainerRef.value.querySelector('.u-ruler')
    const slotsEl = scrollContainerRef.value.querySelector('.slots-container')
    if (rulerEl && slotsEl) {
      const height = `calc(var(--u-height) * ${props.totalU})`
      rulerEl.style.height = height
      slotsEl.style.height = height
    }
  }
})
</script>

<style scoped lang="scss">
.cabinet-view {
  --cabinet-width: 280px;
  --u-height: 32px;
  --ruler-width: 36px;
  --visible-u-count: 10;

  .cabinet-container {
    display: flex;
    height: calc(var(--visible-u-count) * var(--u-height));
    border: 3px solid #2c3e50;
    border-radius: 4px;
    background: linear-gradient(90deg, #34495e, #2c3e50);
    padding: 6px;
    overflow: hidden;

    .scroll-container {
      display: flex;
      height: 100%;
      overflow-y: scroll;
      scrollbar-width: none;
      -ms-overflow-style: none;
      &::-webkit-scrollbar {
        display: none;
      }

      // 内容容器
      .u-ruler,
      .slots-container {
        min-height: 100%;
        padding: 0;
      }

      .u-ruler {
        width: var(--ruler-width);
        display: flex;
        flex-direction: column-reverse;

        .u-number {
          height: var(--u-height);
          min-height: var(--u-height);
          display: flex;
          align-items: center;
          justify-content: flex-end;
          color: rgba(255, 255, 255, 0.9);
          font-size: 13px;
          user-select: none;
          position: relative;

          span {
            position: absolute;
            right: 8px;
            height: 100%;
            display: flex;
            align-items: center;
          }
        }
      }

      .slots-container {
        width: var(--cabinet-width);
        display: flex;
        flex-direction: column-reverse;
        position: relative;
      }
    }

    .slot {
      height: var(--u-height);
      min-height: var(--u-height);
      background: #fff;
      border: 1px solid #dcdfe6;
      flex-shrink: 0;
      transition: all 0.2s;
      position: relative;
      z-index: 1;

      .slot-content {
        height: 100%;
        display: flex;
        align-items: center;
        padding: 0 6px;
        gap: 4px;

        .mount-holes {
          display: flex;
          gap: 6px;
          .hole {
            width: 4px;
            height: 4px;
            border-radius: 50%;
            background: #999;
            border: 1px solid #666;
          }
        }

        .device-name {
          flex: 1;
          text-align: center;
          font-size: 13px;
          color: var(--el-color-primary);
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      &.occupied {
        background: #ffebeb;
        border-color: #f56c6c;
        cursor: not-allowed;
        .device-name {
          color: #f56c6c;
          font-weight: 500;
        }
      }

      &.selected {
        background: var(--el-color-primary-light-7) !important;
        border: 1px solid var(--el-color-primary);
        position: relative;
        z-index: 1;
        box-shadow: 0 0 0 1px var(--el-color-primary);

        &:not(:last-child) {
          border-bottom-color: transparent;
        }

        &:last-of-type {
          border-bottom-color: var(--el-color-primary);
        }

        .device-name {
          color: var(--el-color-primary-dark-2);
          font-weight: 500;
        }

        &::before {
          content: '';
          position: absolute;
          left: -2px;
          right: -2px;
          top: 0;
          bottom: 0;
          background: var(--el-color-primary-light-8);
          pointer-events: none;
          z-index: -1;
        }
      }

      &.selectable {
        background: #f0f9eb;
        border: 1px solid #85ce61;
      }

      &.disabled {
        background: #f5f7fa;
        border: 1px solid #dcdfe6;
        cursor: not-allowed;

        .device-name {
          color: #909399;
        }
      }
    }
  }

  .legend {
    margin-top: 8px;
    display: flex;
    justify-content: center;
    gap: 12px;

    .legend-item {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 12px;

      .color-block {
        width: 14px;
        height: 14px;
        border-radius: 2px;

        &.occupied {
          background: #ffebeb;
          border: 1px solid #f56c6c;
        }

        &.selected {
          background: var(--el-color-primary-light-7);
          border: 1px solid var(--el-color-primary);
        }

        &.selectable {
          background: #f0f9eb;
          border: 1px solid #85ce61;
        }

        &.disabled {
          background: #f5f7fa;
          border: 1px solid #dcdfe6;
        }
      }
    }
  }
}
</style>
